package nexd.com.employ.presenter;

import android.app.Activity;
import android.content.Context;
import android.graphics.PointF;
import android.text.TextUtils;
import android.util.Log;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ScheduledThreadPoolExecutor;

import cn.nexd.framework.util.Logger;
import cn.nexd.map.rendering.core.componet.SVGMapView;
import cn.nexd.map.rendering.overlay.SVGMapLocationOverlay;
import nexd.com.employ.Config;
import nexd.com.employ.overly.MorePointOverly;
import nexd.com.employ.ui.iView.INexdMapView;


/**
 * Created by wangxu on 16/4/26.
 */
public class NexdMapPresenter extends BasePresenter<INexdMapView> {

    private static final String TAG = NexdMapPresenter.class.getSimpleName();
    private static final String REQUEST_LOCATION_COORDINATE = "request_location_coordinate";
    private static final int LOCATION_OVERLY = 1;
    private RequestQueue requestQueue;//这里的this指的是Context
    private static String BASE_MAP_PATH;
    private SVGMapLocationOverlay svgMapLocationOverlay; // 定位图层

    private MorePointOverly morePointOverly;
    private SVGMapView nexdMap;

    private int currentCount = 0;

    private Map<String, PointF> positions;

    private ScheduledThreadPoolExecutor executor;

    public NexdMapPresenter(Context context, INexdMapView iView) {
        super(context, iView);
        requestQueue = Volley.newRequestQueue(context);
        positions = new HashMap<>();
//        BASE_MAP_PATH = Config.BASE_FILE_PATH + "10108058" + File.separator;
        BASE_MAP_PATH = Config.BASE_FILE_PATH + "10258201" + File.separator;
        executor = new ScheduledThreadPoolExecutor(1);
        Logger.isDebug(true);
    }

    public void setNexdMap(SVGMapView nexdMap) {
        this.nexdMap = nexdMap;
    }

    public void loadMap() {
        Log.d(TAG, "loadMap: 开始加载地图\n" + getSvgPath());
        iView.loadMap(getSvgPath());
    }

    //    private String getSvgPath() {
//        return BASE_MAP_PATH + "101080580001.svg";
//    }
    private String getSvgPath() {
        return BASE_MAP_PATH + "102582010001.svg";
    }

    // 请求定位点,获取线上定位坐标,更新在地图上
    public void requestLocation() {

        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        iView.updateOthers(String.valueOf(currentCount));
                    }
                });
            }
        }, 500, 1000);

        StringBuilder url = new StringBuilder();
        url.append(Config.BASE_IP)
                .append("?appKey=")
                .append(Config.APP_KEY);
        Log.d(TAG, "requestLocationCoordinate: " + url.toString());

        StringRequest uploadLocationCoordinate = new StringRequest(Request.Method.POST, url.toString(), new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                if (!TextUtils.isEmpty(s)) {
                    Log.d(TAG, "onResponse: " + s);

                    try {
                        JSONObject jsonObject = new JSONObject(s);

                        if (jsonObject.getBoolean("isSuccess")) {

                            JSONObject firstObject = jsonObject.getJSONObject("locationMap");


                            Iterator iterator = firstObject.keys();

                            while (iterator.hasNext()) {
                                String key = (String) iterator.next();
                                JSONObject map = new JSONObject(firstObject.getString(key));
                                positions.put(key, new PointF((float) map.getDouble("x"), (float) map.getDouble("y")));
                            }

                            currentCount = positions.size();

//                            for (Map.Entry<String, PointF> entry : positions.entrySet()) {
//                                if (!positionColor.containsKey(entry.getKey())) {
//                                    LocationModel locationModel = new LocationModel();
//                                    locationModel.setMachineImei(entry.getKey());
//                                    locationModel.setColor(colors[positionColor.size()]);
//                                    locationModel.setLocation(entry.getValue());
//                                    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
//                                    paint.setAntiAlias(true);
//                                    paint.setStyle(Paint.Style.FILL);
//                                    paint.setColor(Color.parseColor(colors[positionColor.size()]));
//                                    locationModel.setLocalPaint(paint);
//                                    positionColor.put(entry.getKey(), locationModel);
//                                } else {
//                                    positionColor.get(entry.getKey()).setLocation(entry.getValue());
//                                }
//                            }


                            if (morePointOverly == null) {
                                morePointOverly = new MorePointOverly(context, nexdMap);
                                nexdMap.addOverlay(morePointOverly, LOCATION_OVERLY);
                            }
                            morePointOverly.setPositions(positions);
                            nexdMap.refresh();
//                            iView.addMapOverly(morePointOverly, LOCATION_OVERLY);
                        }

//                        if (jsonObject.getBoolean("isSuccess")) {
//                            JSONObject map = jsonObject.getJSONObject("locationMap");
//                            Log.d(TAG, "onResponse: " + map.toString());
//                            map.
//                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


//                    try {
//                        JSONObject resultJson = new JSONObject(s);
//                        if (resultJson.getBoolean("isSuccess")) {
//                            if (positions == null) {
//                                positions = new HashMap<>();
//                            } else {
//                                positions.clear();
//                            }
//
//
//
//                            float x = Float.parseFloat(resultJson.getString("x"));
//                            float y = Float.parseFloat(resultJson.getString("y"));
//
//                            if (morePointOverly==null) {
//                                morePointOverly = new MorePointOverly(context, nexdMap);
//                            }
////                            morePointOverly.setPositions();
//
//                            if (svgMapLocationOverlay == null) {
//                                svgMapLocationOverlay = new SVGMapLocationOverlay(nexdMap, new PointF(x, y));
//                            } else {
//                                svgMapLocationOverlay.setPosition(new PointF(x, y));
//                            }
//                            iView.addMapOverly(svgMapLocationOverlay, LOCATION_OVERLY);

                    nexdMap.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            requestLocation();
                        }
                    }, 2000);
//                    try {
//                        Thread.sleep(2000);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                    requestLocation();
//                        }
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                requestLocation();
            }
        });

        cancelPendingRequests(REQUEST_LOCATION_COORDINATE);
        uploadLocationCoordinate.setRetryPolicy(new DefaultRetryPolicy(1000, 0, 0f));
        uploadLocationCoordinate.setTag(REQUEST_LOCATION_COORDINATE);
        requestQueue.add(uploadLocationCoordinate);
    }


    // 通过各Request对象的Tag属性取消请求
    private void cancelPendingRequests(Object tag) {
        if (requestQueue != null) {
            requestQueue.cancelAll(tag);
        }
    }
}
